// 将标准输出重定向到文件My.file的程序
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

#define CREATE_FLAGS (O_WRONLY | O_CREAT | O_APPEND)
#define CREATE_MORE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)

int main (void) {
    int fd;

    fd = open("my.file", CREATE_FLAGS, CREATE_MORE);
    if (fd == -1) {
        perror("Failed to open my.file");
        return -1;
    }

    // 将fd重定向到标准输出中
    int ret = dup2(fd, STDOUT_FILENO);
    if (ret == -1) {
        perror("Failed to redirect standart output");
        return -1;
    }

    if (close(fd) == -1) {
        perror("Failed to close the file");
        return -1;
    }

    // 在该文件后面附加消息
    ret = write(STDOUT_FILENO, "THIS IS OOOOOO\n", 15);
    if (ret == -1) {
        perror("Failed in writing to file");
        return -1;
    }

    return 0;
}